#  分店
class Studio < ApplicationRecord
  validates_presence_of :name, :company_id, :invalidate_at
  #validates_uniqueness_of :name, scope: :company_id

  # kevin，验证同一公司下，分店名称唯一性，暂时关闭
  # validates :name, uniqueness: {scope: [:company_id]}

  #default_values uuid: -> { SecureRandom.hex }

  # 分店设置
  has_many :course_room_configurations
  has_and_belongs_to_many :finances, join_table: 'studios_finances', foreign_key: 'studio_id'
  has_and_belongs_to_many :fixed_costs, join_table: 'fixed_costs_studios'

  has_many :students
  has_many :potential_students
  belongs_to :company
  has_many :employees, :through => :employee_of_studios
  has_many :orders
  has_many :student_orders, :through => :students 
  has_many :course_reckons
  has_many :finances
  has_many :potential_orders, through: :potential_students 
  has_many :employee_of_studios
  #accepts_nested_attributes_for :employees
  def targets_of_month(month, position_name)
    all = Target.month_target(month)
    if all.blank?
      return '-'
    else
      es_ids = self.employee_of_studios.map { |es| es.id if es.position_configuration.position_name == position_name  }.compact
      if es_ids.blank?
        return '-'
      else
        this_month =  all.where(studio_id: self.id).where("employee_of_studio_id IN  (#{es_ids.join(',')})")
        if this_month.blank?
          return '-'
        else
          return this_month.map {|tg| tg.amount }.inject(0) {|sum, item| sum + item}
        end
      end
    end
  end

  def studio_target_of_month(month, director)
    targets = Target.where(employee_of_studio_id: director, studio_id: self.id).month_target(month)
    if targets.blank?
      return "-"
    else
      return targets.map {|tg| tg.amount }.inject(0) {|sum, item| sum + item}
    end
  end
end
